package com.wx.util;//package com.cn.wanxi.util;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class MyFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {//init 启动时执行

    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req= (HttpServletRequest) servletRequest;
        HttpServletResponse resp= (HttpServletResponse) servletResponse;
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");


//        //用于判断request来自ajax还是传统请求
        resp.setHeader("Access-Control-Allow-Headers", "Origin,X-Requested-With,Content-Type,Accept");
        resp.setContentType("application/json");
        /* 允许跨域的主机地址 */
//        resp.setHeader("Access-Control-Allow-Origin", "http://localhost:63343");
        resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));//所有端口可访问
        /* 允许跨域的请求方法GET, POST, HEAD 等 */
        resp.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
        /* 重新预检验跨域的缓存时间 (s) */
        resp.setHeader("Access-Control-Max-Age", "3600");
        /* 允许跨域的请求头 */
        resp.setHeader("Access-Control-Allow-Headers", "Content-Type , Content-Length , Access-Token , Authorization , Accept , X-Requested-With , X-Custom-Header , Request-Ajax , yourHeaderFeild");
        /* 是否携带cookie */
        resp.setHeader("Access-Control-Allow-Credentials", "true");
        resp.setHeader("XDomainRequestAllowed", "1");
        //内容类型：如果是post请求必须指定这个属性
        resp.setHeader("Content-Type", "application/json;charset=utf-8");


        String url=req.getServletPath();//到访问路径
//url.endsWith("/a/")以a结尾
//url.startsWith("/b/" )以b开始
        if (url.startsWith("/user" ) || url.startsWith("/company") || url.startsWith("/back")){
            String username= (String) req.getSession().getAttribute("username");//得到session
            if (username == null){
                resp.getWriter().println(400);
            }else {
                filterChain.doFilter(req,resp);//放行操作
            }
        }else {
            filterChain.doFilter(req,resp);//放行操作
        }
    }

    @Override
    public void destroy() {//结束时运行

    }
}
